package com.itheima.SpringRabbit;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.Item;
import com.hmall.feignconfig.itemClient;
import com.itheima.dto.ItemDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class SpringRabbitListener {


    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private com.hmall.feignconfig.itemClient itemClient;


    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage(Map map) throws IOException {

        Long id = (Long)map.get("id");
        Integer status = (Integer) map.get("status");

        if (status != 1){
            //删除文档
            DeleteRequest request = new DeleteRequest("mall").id(id.toString());
            client.delete(request, RequestOptions.DEFAULT);
        }else {
            // 1.根据id查询数据
            Item byId = itemClient.getById(id);
            // 2.转换为文档类型
            ItemDoc hotelDoc = new ItemDoc(byId);
            // 3.将HotelDoc转json
            String json = JSON.toJSONString(hotelDoc);

            IndexRequest request = new IndexRequest("mall").id(id.toString());
            request.source(json, XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
        }
    }
}
